<template>
  <div class="upload">
    <PreviewComp
      :imgList="rec.fileUrls"
      :videoList="rec.video"
      @delImg="delImg"
      @delVideo="delVideo"
      :delFlag="true"
    />
    <van-uploader
      :multiple="true"
      :accept="
        rec.video.length
          ? 'image/jpeg,image/jpg,image/png,image/gif'
          : 'image/jpeg,image/jpg,image/png,image/gif,video/mp4'
      "
      :before-read="handleBeforeFile"
      :after-read="handleUploadFile"
    >
      <div class="upload-box">
        <svg-icon icon-class="addImg" />
        <div class="upload-box-word">上传视频、照片</div>
      </div>
    </van-uploader>
  </div>
</template>
<script lang="ts" setup>
import { reactive } from "vue";
import { isArray } from "@/utils/is";
// import { isImage } from "@/utils/utils";
import { Toast } from "vant";
import LocalCache from "@/utils/cache";
import { uploadFile } from "@/service/modules/public/public";
import PreviewComp from "@/components/previewComp/index.vue";
import * as imageConversion from "image-conversion";

const rec = reactive({
  fileUrls: [],
  video: [],
});
const {
  accessToken = "",
  appToken = "",
  //   name,
  //   personId,
  //   mobile,
} = LocalCache.getSession("userInfo");
const imgType = ["jpg", "jpeg", "png", "gif", "heic", "heif"];
// 文件上传前
const handleBeforeFile = (file) => {
  const fileLen =
    rec.fileUrls.length +
    rec.video.length +
    (file.length === undefined ? 1 : file.length);
  if (fileLen > 9 || file.length > 9) {
    Toast.fail("请留意单次报修最多上传9张照片和视频");
    return false;
  }

  const Limit_SIZE_IMG = 32 * 1024 * 1024;
  const Limit_SIZE_VIDEO = 320 * 1024 * 1024;
  if (isArray(file)) {
    const videoObj = file.find((i) => i.type === "video/mp4");
    const imgArray = file.filter((i) => i.type !== "video/mp4");
    if (videoObj !== undefined) {
      if (videoObj.size > Limit_SIZE_VIDEO) {
        Toast.fail("视频超出320MB大小限制，请重新上传");
        return false;
      }
    }
    // 图片size数组
    const imgSizes = imgArray.map((item) => item.size);
    if (imgSizes.some((item) => item > Limit_SIZE_IMG)) {
      Toast.fail("照片超出32MB大小限制，请重新上传");
      return false;
    }
  } else {
    const { size, type } = file;
    if (type === "video/mp4") {
      if (size > Limit_SIZE_VIDEO) {
        Toast.fail("视频超出320MB大小限制，请重新上传");
        return false;
      }
    } else {
      // 图片
      if (size > Limit_SIZE_IMG) {
        Toast.fail("照片超出32MB大小限制，请重新上传");
        return false;
      }
    }
  }
  return true;
};
// 文件上传成功
const handleUploadFile = async (file) => {
  Toast.loading({
    message: "加载中...",
    forbidClick: true,
    loadingType: "spinner",
  });
  let fileList = [];
  if (isArray(file)) {
    fileList = [...file];
  } else {
    fileList.push(file);
  }
  const headers = {
    appToken,
    accessToken,
    operateCode: "test",
  };
  const uploadFileApiList = [];

  for (const item of fileList) {
    // 压缩图片大小
    const newImgFile = await compressImg(item.file);
    const formData = new FormData();
    formData.append("file", newImgFile, item.file.name);
    formData.append("catalog", "A");
    // console.log(formData, "formData");
    // newImgFile.append("catalog", "A");

    uploadFileApiList.push(uploadFile(headers, formData));
  }

  // fileList.forEach((item) => {
  //   const newImgFile = await compressImg(item.file)
  //   const formData = new FormData();
  //   formData.append("file", newImgFile, item.file.name);
  //   formData.append("catalog", "A");
  //   console.log(formData, "formData");
  //   // newImgFile.append("catalog", "A");

  //   uploadFileApiList.push(uploadFile(headers, formData));
  // });
  const res = await Promise.allSettled(uploadFileApiList);
  const imgs = [...rec.fileUrls];
  res.forEach((item) => {
    if (item.status === "fulfilled" && item.value?.status === 200) {
      if (imgType.includes(item.value.result.type)) {
        // 图片
        imgs.push(item.value.result.url);
      } else {
        rec.video = [item.value.result.url];
      }
    } else {
      Toast.fail(item.value?.message || "上传失败，请重试");
    }
  });
  rec.fileUrls = imgs;
  // console.log(rec.fileUrls, "fileUrls");
};
// 删除图片
const delImg = (idx) => {
  rec.fileUrls = rec.fileUrls.filter((i, index) => index !== idx);
};
// 删除视频
const delVideo = () => {
  rec.video = [];
};

// 压缩图片
const compressImg = (file) => {
  return new Promise((resolve) => {
    // 超过200kb就压缩
    if (file.size / (1024 * 1024) > 0.2) {
      imageConversion.compressAccurately(file, 200).then((res) => {
        console.log(res, "exerer");
        resolve(res);
        // transToFile(res).then((res2) => {
        //   resolve(res2);
        // });
      });
    } else {
      resolve(file);
    }
  });
};

defineExpose({
  rec,
});
</script>
<style lang="less" scoped>
.upload {
  /deep/ .van-uploader {
    margin-top: 16px;
    margin-bottom: 12px;
    border-radius: 4px;
    border: 0.5px solid #e1e5ea;
  }

  .upload-box {
    height: 100px;
    width: 100px;
    display: flex;
    align-items: center;
    flex-direction: column;
    justify-content: center;

    &-word {
      margin-top: 10px;
      font-size: 12px;
      line-height: 14px;
      color: #919599;
    }
  }
}
</style>
